#include "net.hpp"
#include "dispatcher.hpp"

void OnMessage(const MyRpc::BaseConnection::ptr& conn, const MyRpc::RpcRequest::ptr& msg)
{
    // 服务端收到消息之后的回调函数
    LOG(DEBUGLEVEL, "进入到服务端对消息进行处理的函数!");
    std::string body;
    bool flag = msg->serialize(body);
    if(flag == false)
    {
        LOG(DEBUGLEVEL, "消息序列化失败");
        return;
    }
    std::cout << body << std::endl;
    // 由于msg是基类 所以不能调用子类的函数 但是通过强制转化之后就可以调用了
    // 但是这种方式对使用者不友好 所以用模板来进行实现
    auto req_msg = std::dynamic_pointer_cast<MyRpc::RpcRequest>(msg);
    std::cout << "客户端请求方法: " << req_msg->method() << std::endl;
    // 构建应答发送给客户端
    MyRpc::RpcResponse::ptr sendmsg = MyRpc::MessageFactory::create<MyRpc::RpcResponse>();
    sendmsg->setId(MyRpc::UUID::uuid());
    sendmsg->setMType(MyRpc::MType::RSP_RPC);
    sendmsg->setRcode(MyRpc::RCode::RCODE_OK);
    Json::Value res;
    res[KEY_RESULT] = 33;
    sendmsg->setResult(res);
    // 然后把刚才构造的应答发送给客户端
    flag = conn->send(sendmsg);
    if(flag == false)
    {
        LOG(DEBUGLEVEL, "发送应答失败!");
        return;
    }
    LOG(DEBUGLEVEL, "发送应答成功!");
}

int main()
{
    MyRpc::BaseServer::ptr server = MyRpc::ServerFactory::create(9090);    
    server->setMessageCallBack(std::bind(&MyRpc::Dispatcher::OnMessage, MyRpc::disp.get(), std::placeholders::_1, std::placeholders::_2));
    MyRpc::disp->Register<MyRpc::RpcRequest>(MyRpc::MType::REQ_RPC, OnMessage);
    // server->setMessageCallBack(OnMessage);
    server->start();

    return 0;
}